module executor.rpc.action.ContactAction;

import msgtrans;
import message.Constants;
import message.MsgDefine;
import google.protobuf;
import hunt.logging;
import std.array;
import std.conv : to;
import comm.comm;
import executor.rpc.dto.ContactApplyDto;
import executor.rpc.dto.UserDto;
import hunt.serialization;
import client.GateServerClient;
import client.MsgServerClient;
import service.ContactsService;
import service.ApplyService;
import repository.FriendRepository;
import repository;
import model;

string ContactAgree(string userId, string content)
{
    auto apply = toObject!ContactApplyDto(content);
    string fromId = apply.fromId;

    logInfof("User %s accept %s friend apply....", userId, fromId);

    auto friendApplyRepo = new FriendApplyRepository;
    FriendApply firendApply = friendApplyRepo.findApply(fromId, userId);
    if (firendApply is null)
    {
        return RPCResponseErrorEncode(20201, "好友申请已过期，重新申请。。");
    }

    string chatId = firendApply.id.to!string;

    UserRepository userRepo = new UserRepository;
    model.User user = userRepo.findAllByUID(fromId);
    if (user is null)
    {
        return RPCResponseErrorEncode(20001, "用户数据获取错误。");
    }

    if (apply.agree) //同意添加好友
    {
        if (!ApplyService.agree(firendApply))
        {
            return RPCResponseErrorEncode(20203, "处理同意好友申请出现问题，请联系管理员。");
        }
    }

    ApplyService.updateApplyContactReq(chatId, apply.agree ? 1: 2); //更新表状态同意or忽略

    UserDto userDto;
    userDto.uid = user.id.to!string;
    userDto.chatId = chatId;
    userDto.name = user.nickname;
    userDto.aliasName = "";
    userDto.avatar = user.avatar;
    userDto.gender = user.gender;
    userDto.birthday = user.birthday;
    userDto.addValidation = 0;
    userDto.lastMsgRead = 0;
    userDto.mobile = user.mobile;
    userDto.qrcode = user.qrcode;
    userDto.userName = user.username;
    userDto.src = cast(ContactApplySrc)firendApply.src;

    return RPCResponseEncode(userDto.toJson);
}
